package com.wawayaya.db.bookshelf;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.wawayaya.api.ApiResponseData;
import com.wawayaya.api.remote.ApiConstans;
import com.wawayaya.bean.Area;
import com.wawayaya.bean.Banner;
import com.wawayaya.bean.BookShelf;
import com.wawayaya.bean.Books;
import com.wawayaya.bean.Config;
import com.wawayaya.bean.MyBookShelf;
import com.wawayaya.bean.Notice;
import com.wawayaya.bean.Support;
import com.wawayaya.bean.Timestamp;
import com.wawayaya.bean.User;
import com.wawayaya.db.entitydao.AreaEntityDao;
import com.wawayaya.db.entitydao.BannerEntityDao;
import com.wawayaya.db.entitydao.BookEntityDao;
import com.wawayaya.db.entitydao.BookShelfEntityDao;
import com.wawayaya.db.entitydao.ConfigEntityDao;
import com.wawayaya.db.entitydao.NoticeEntityDao;
import com.wawayaya.db.entitydao.SupportEntityDao;
import com.wawayaya.db.entitydao.UserEntityDao;
import com.wawayaya.util.TLog;

/**
 * Created by david on 15/8/24.
 */
public class ShelfLoadThread extends Thread{
    private static final String  TAG = "LoadThread";
    private Handler  reqHandler;
    private  Handler  cHandler;

    public ShelfLoadThread(){}

    public void setReqHandler(Handler reqHandler) {
        this.reqHandler = reqHandler;
    }

    public Handler getcHandler() {
        return cHandler;
    }
    @Override
    public void run() {
        super.run();
        Looper.prepare();
        cHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case ApiConstans.USER_LOGIN:
                    case ApiConstans.USER_REGISTER:
                    case ApiConstans.LOGINJOYREADER:
                        userOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.DEVICE:
                        userDeviceOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.CONFIG:
                        configOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.BANNER:
                        bannerOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.BOOKSHELF:
                        bookShelfOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.AREA:
                        areaOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.BOOK:
                        bookByShelfOperate((ApiResponseData) msg.obj);
                        break;

                    case ApiConstans.NOTICE:
                        noticeOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.SUPPORT:
                        supportOperate((ApiResponseData)msg.obj);
                        break;
                };
            }
        };
        Looper.loop();
    }


    private synchronized void supportOperate(final ApiResponseData  data){
        SupportEntityDao supportFileDao = new SupportEntityDao();
        Support support =  new Support();
        try{
            if(null!=data.getUpdateAry()){

                for(int i=0;i<data.getUpdateAry().length();i++){
                    support = ((Support)support.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    supportFileDao.replaceEntity(support);
                    Log.e(TAG, "返回supportfile...." + support.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    supportFileDao.deleteEntityByKey(jo.optString("sfKey"));
                }
            }
         /*   Timestamp timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setSupportFile(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
            //reqHandler.sendEmptyMessage(ApiConstans.MYBOOKSHELF);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }


    private synchronized void  noticeOperate(final ApiResponseData  data){
        NoticeEntityDao noticeDao = new NoticeEntityDao();
        Notice   versionNotice= null;
        try{
            if(null!=data.getUpdateAry()){
                Notice notice =  new Notice();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    notice =  ((Notice)notice.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    noticeDao.replaceEntity(notice);
                    //  Log.e(TAG,"返回noticeOperate...."+notice.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo =data.getDeleteAry().optJSONObject(i);
                    noticeDao.deleteEntityByKey(jo.optLong("noticeId"));
                }
            }
           /* Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setNotice(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
           Message  message =  reqHandler.obtainMessage();
               message.what = ApiConstans.BANNER;
            reqHandler.sendMessage(message);
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    private synchronized  void  bookByShelfOperate(final ApiResponseData  data){
        BookEntityDao booksDao =new BookEntityDao();
        try{
            if(null!=data.getUpdateAry()){
                Books book =  new Books();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    book = ((Books)book.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    booksDao.replaceEntity(book);
                    // Log.e(TAG,"返回 book ...."+book.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    booksDao.deleteEntityByKey(jo.optInt("bookId"));
                }
            }
            //update timestamp
           /* Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setBooks(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/

           // reqHandler.sendEmptyMessage(ApiConstans.endData);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }


    /**
     * 未修改
     * @param data
     */
    private synchronized  void  bookShelfOperate(final ApiResponseData  data){
        BookShelfEntityDao shelfDao = new BookShelfEntityDao();
        try{

            if(null!=data.getUpdateAry()){
                BookShelf shelf =  new BookShelf();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    shelf = ((BookShelf)shelf.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    shelfDao.replaceEntity(shelf);
                    //Log.e(TAG,"返回 book ...."+shelf.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    shelfDao.deleteEntityByKey(jo.optLong("bsId"));
                }
            }
          /*  Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setBookSelf(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);
*/
            reqHandler.sendEmptyMessage(ApiConstans.BOOK);
        }catch (JSONException e){
            e.printStackTrace();
        }

    }


    private synchronized void  configOperate(final ApiResponseData  data){
        ConfigEntityDao configDao = new ConfigEntityDao();
        Config config =  new Config();
        try{
            if(null!=data.getUpdateAry()){

                for(int i=0;i<data.getUpdateAry().length();i++){
                    config =  ((Config)config.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    configDao.replaceEntity(config);
                    TLog.log(TAG,"返回 configOperate ...."+config.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    config =  ((Config)config.clone()).jsonToVO((JSONObject)data.getDeleteAry().get(i));
                    configDao.deleteEntityByKey(config.getValue());
                }
            }
            TLog.log("config存储完成......");
          /*  Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setConfig(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
           // reqHandler.sendEmptyMessage(ApiConstans.NOTICE);
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    private synchronized void  bannerOperate(final ApiResponseData  data){
        BannerEntityDao bannerDao = new BannerEntityDao();
        Banner banner =  new Banner();
        try{
            if(null!= data.getUpdateAry()){

                for(int i=0;i< data.getUpdateAry().length();i++){
                    banner =  ((Banner)banner.clone()).jsonToVO((JSONObject) data.getUpdateAry().get(i));
                    Log.e("bannerOperate", "返回 bannerOperate........." + banner.toString());
                    bannerDao.insertOrReplaceByWhere(banner);
                }
            }
            if(null!=data.getDeleteAry()){
                //Log.e("DBManager","array...delete ......"+data.getDeleteAry());
                for(int i=0;i< data.getDeleteAry().length();i++){
                    banner =  ((Banner)banner.clone()).jsonToVO((JSONObject) data.getDeleteAry().get(i));
                    bannerDao.deleteEntityByKey(banner.getBannerId());
                }
            }
         /*   Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setBanner(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
            reqHandler.sendEmptyMessage(ApiConstans.SUPPORT);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    private synchronized void  areaOperate(final ApiResponseData  data){
        AreaEntityDao areaEntityDao = new AreaEntityDao();
        Area area = new Area();
        try{
            if(null!=data.getUpdateAry()) {
                for (int i = 0; i < data.getUpdateAry().length(); i++) {
                    area = ((Area) area.clone()).jsonToVO((JSONObject) data.getUpdateAry().get(i));
                    areaEntityDao.replaceEntity(area);
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i< data.getDeleteAry().length();i++){
                    area =  ((Area)area.clone()).jsonToVO((JSONObject)data.getDeleteAry().get(i));
                    areaEntityDao.deleteEntityByKey(area.getAreaId());
                    //Log.e(TAG, "返回 configOperate ...." + area.toString());
                }
            }
            /*Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setArea(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    private synchronized void  userOperate(final ApiResponseData  data){
        UserEntityDao userEntityDao = new UserEntityDao();
        User user = new User().jsonToVO(data.getRetinfo());
        Log.e("userinfor", "userid:" + user.getUserId());
        try{
            if(null==data.getDeleteAry()){
                // Log.e(TAG,"返回 userOperate ...."+user.toString());
                userEntityDao.replaceEntity(user);
            }

            /*Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setUsers(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
          //  reqHandler.sendEmptyMessage(ApiConstans.CONFIG);
        }catch(Exception  e){
            e.printStackTrace();
        }
    }

    private synchronized void  userDeviceOperate(final ApiResponseData  data){
        UserEntityDao  userEntityDao = new UserEntityDao();
        User user = new User().jsonToVO(data.getRetinfo());
        //Log.e("userinfor","userid:"+user.getUid()+" device emdial:"+user.getEmail());
        try{
            //  Log.e(TAG,"返回 userOperate ...."+user.toString());
            userEntityDao.replaceEntity(user);

         /*   Timestamp  timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setUsers(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
            reqHandler.sendEmptyMessage(ApiConstans.CONFIG);
        }catch(Exception  e){
            e.printStackTrace();
        }
    }
}
